/**
 * @version 1.0
 * @author Shaun Chyxion <br />
 * chyxion@163.com
 * Dec 05, 2014 11:39:58
 */
Ext.define ('SpringExt.views.CodeGen', {
    extend: 'Ext.container.Container',
    title: 'Auto Code',
    layout: 'border',
    items: [{
        xtype: 'treepanel',
        region: 'west',
        split: true,
        width: 186,
        hideHeaders: true,
        tbar: [{
            text: 'Remove Model',
            name: 'btn_remove',
            disabled: true,
            iconCls: 'remove',
            handler: function () {
                var t = this.up('treepanel'),
                    nodes = t.getView().getChecked();
                Dialog.confirm('Are You Sure To Remove Model(s) Selected?', function() {
                    var items = [];
                    Ext.Array.each(nodes, function(rec) {
                        items.push({
                            module: rec.get('module'),
                            model: rec.get('model')
                        });
                    });
                    if (!items.length) {
                        var rec = t.getSelectionModel().getLastSelected();
                        items.push({
                            module: rec.get('module'),
                            model: rec.get('model')
                        });
                    }
                    Ajax.del('codegen', {
                        items: items
                    }, function() {
                        t.getStore().reload();
                        // right container
                        var rc = t.next('container'),
                            form = rc.down('form');
                        form.getForm().reset();
                        form.down('grid').getStore().removeAll();
                        // remove demo grid
                        rc.down('container[name=demo_grid]').removeAll();
                        Message.alert('Remove Success.');
                    });
                });
            }
        }],
        store: Store.tree({
            url: 'codegen/list',
            fields: ['text', 'name', 'module', 'model', 'cols', 'table'],
            root_text: 'Models'
        }),
        listeners: {
            select: function(rm, rec) {
                this.down('toolbar')
                    .down('button[name=btn_remove]')
                    .setDisabled(!rec.isLeaf());
                if (rec.isLeaf()) {
                    // right container
                    var rc = this.next('container');
                        form = rc.down('form');
                    form.getForm().setValues(rec.getData());
                    form.down('grid').getStore().loadData(rec.get('cols'));
                    // show demo grid
                    var dg = rc.down('container[name=demo_grid]');
                    dg.removeAll();
                    // load view
                    dg.add(Ext.create('App.views.' +
                        (rec.get('module') ? rec.get('module') + '.' : '') + 
                        rec.get('model') + '.List'));
                }
            }
        }
    }, {
        xtype: 'container',
        region: 'center',
        layout: 'border',
        items: [{
            xtype: 'form',
            region: 'north',
            split: true,
            height: 312,
            autoScroll: true,
            bodyPadding: 12,
            layout: 'vbox',
            defaults: {
                width: '96%',
                labelWidth: 86
            },
            tbar: [{
                text: 'Generate!',
                iconCls: 'save',
                handler: function(btn) {
                    var form = btn.up('form');
                    if (form.isValid()) {
                        var s = form.down('grid').getStore();
                        if (s.getCount()) {
                            var params = form.getForm().getValues(),
                                columns = [];
                            s.each(function(rec) {
                                columns.push(rec.getData());    
                            });
                            params.columns = columns;
                            Dialog.confirm('Are You Sure To Submit?', function() {
                                Ajax.post('codegen', params, function() {
                                    form.up('container')
                                        .previousNode('treepanel')
                                        .getStore()
                                        .reload();
                                    Message.alert('Generate Success.');
                                });
                            });
                        }
                        else {
                            Message.warn('Please Add Columns.');
                        }
                    }
                }
            }],
            items: [{
                xtype: 'box',
                html: [
                    '<span style="color: #333;">Note: </span>',
                    'Model Properties ',
                    '<strong style="color: #F00;">',
                    'id, dateCreated, dateUpdated',
                    '</strong> ',
                    'Will Be Generated Automatically, ',
                    'Please ',
                    '<strong style="color: #F00;">',
                    'Do Not</strong> ',
                    'Add Duplicately.',
                ].join(''),
                padding: '0 0 12 0',
                style: {
                    fontSize: '12pt',
                    color: '#00F'
                },
            }, {
                xtype: 'fieldcontainer',
                fieldLabel: 'Columns',
                items: {
                    xtype: 'grid',
                    minHeight: 128,
                    plugins: [Ext.create('Ext.grid.plugin.CellEditing', { 
                        clicksToEdit: 1 
                    })],
                    store: {
                        store: 'json',
                        fields: ['name', 'javaType', 'sqlType', 'notNull']
                    },
                    columns: [{
                        xtype: 'rownumberer'
                    }, {
                        dataIndex: 'name',
                        text: 'Property Name',
                        width: 128,
                        editor: {
                            xtype: 'textfield',
                            allowBlank: false,
                            regex: /^(?!id)|(?!dateCreated)|(?!date_created)|(?!dateUpdated)|(?!date_updated)$/i,
                            regexText: '[id, dateCreated, dateUpdated] Will Be Generated Automatically.'
                        }
                    }, {
                        dataIndex: 'javaType',
                        text: 'Java Type',
                        flex: 1,
                        editor: {
                            xtype: 'combo',
                            typeAhead: true,
                            editable: false,
                            triggerAction: 'all',
                            store: [
                                ['Date', 'Date'],
                                ['String', 'String'],
                                ['boolean', 'boolean'],
                                ['int', 'int'],
                                ['long', 'long'],
                                ['double', 'double']
                            ]
                        }
                    }, {
                        dataIndex: 'sqlType',
                        text: 'SQL Type',
                        flex: 1,
                        editor: {
                            allowBlank: false,
                            xtype: 'combo',
                            typeAhead: true,
                            editable: true,
                            triggerAction: 'all',
                            store: [
                                ['date', 'date'],
                                ['datetime', 'datetime'],
                                ['char(36)', 'char(36)'],
                                ['varchar(36)', 'varchar(36)'],
                                ['bit', 'bit'],
                                ['bigint', 'bigint'],
                                ['int', 'int'],
                                ['float', 'float']
                            ]
                        }
                    }, {
                        dataIndex: 'notNull',
                        text: 'Not Null',
                        width: 76,
                        editor: {
                            xtype: 'checkbox'
                        }
                    }],
                    tbar: [{
                        text: 'Add Column',
                        iconCls: 'add',
                        handler: function () {
                            var g = this.up('grid');
                            g.getStore().add({
                                name: 'name',
                                javaType: 'String',
                                sqlType: 'varchar(36)',
                                notNull: true
                            });
                        }
                    }, {
                        text: 'Remove Column',
                        iconCls: 'remove',
                        handler: function (btn) {
                            var g = btn.up('grid'),
                                ss = g.getSelectionModel().getSelection();
                            if (ss.length) {
                                Dialog.confirm(
                                    'Are You Sure To Remove The Column(s) Selected.', 
                                    function() {
                                        g.getStore().remove(ss);
                                });
                            } 
                            else {
                                Message.warn('Please Select Row(s) To Remove.');
                            }
                        }
                    }]
                }
            }, {
                xtype: 'textfield',
                name: 'module',
                fieldLabel: 'Module'
            }, {
                xtype: 'textfield',
                name: 'model',
                fieldLabel: 'Model',
                value: 'ModelName',
                allowBlank: false
            }, {
                xtype: 'textfield',
                name: 'table',
                fieldLabel: 'Table Name',
                allowBlank: false
            }]
        }, {
            xtype: 'container',
            region: 'center',
            name: 'demo_grid',
            layout: 'fit'
        }]
    }]
});
